package com.weixing.mall.provider.spuuort.wechat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinException;
import org.weixin4j.loader.ITicketLoader;
import org.weixin4j.model.js.Ticket;
import org.weixin4j.model.js.TicketType;

import java.util.concurrent.TimeUnit;

/**
 * @Author: kfc
 * @Description: 微信jsticket工具类<br/>
 * Date:Create in 2018/11/12 14:41
 * @Modified By:
 */
@Component
public class JsTicketLoader implements ITicketLoader {

    private static final String JSTICKET_KEY = "jsTicket";
    private static final String WX_CARD_KEY = "wx_card";

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public Ticket get(TicketType ticketType) {
        Ticket ticket = null;
        if (TicketType.JSAPI.equals(ticketType)) {

            ticket = (Ticket) redisTemplate.opsForValue().get(JSTICKET_KEY);
        } else if (TicketType.WX_CARD.equals(ticketType)) {
            ticket = (Ticket) redisTemplate.opsForValue().get(WX_CARD_KEY);
        }
        if (ticket == null){
            try {
                ticket = new Weixin().getJsApiTicket();
                refresh(ticket);
            } catch (WeixinException e) {
                e.printStackTrace();
            }
        }

        return ticket;
    }

    @Override
    public void refresh(Ticket ticket) {
        if (TicketType.JSAPI.equals(ticket.getTicketType())) {

            redisTemplate.opsForValue().set(JSTICKET_KEY, ticket, 6600L, TimeUnit.SECONDS);
        } else if (TicketType.WX_CARD.equals(ticket.getTicketType())) {
            redisTemplate.opsForValue().set(WX_CARD_KEY, ticket, 6600L,TimeUnit.SECONDS);
        }
    }
}
